package com.ctvit.cch.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctvit.cch.core.mapper.CreativeScriptSceneMapper;
import com.ctvit.cch.core.pojo.domain.CreativeScriptScene;
import com.ctvit.cch.core.pojo.dto.creative.CreativeScriptSceneEditDTO;
import com.ctvit.cch.core.pojo.vo.creative.CreativeScriptSceneListVO;
import com.ctvit.cch.core.service.ICreativeScriptSceneService;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 脚本场景Service业务层处理
 *
 * @author heyingcheng
 * @date 2025/10/11
 */
@Service
public class CreativeScriptSceneServiceImpl extends ServiceImpl<CreativeScriptSceneMapper, CreativeScriptScene>
        implements ICreativeScriptSceneService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sort(List<String> ids) {
        // 按照传入的顺序更新排序字段
        for (int i = 0; i < ids.size(); i++) {
            String sceneId = ids.get(i);
            CreativeScriptScene scene = new CreativeScriptScene();
            scene.setSceneId(sceneId);
            scene.setSceneIndex(i + 1);
            updateById(scene);
        }
        return true;
    }

    @Override
    public List<CreativeScriptSceneListVO> listByShotStatus(String scriptId, String status) {
        // 使用 LambdaQueryWrapper 构造查询条件
        List<CreativeScriptScene> list = list(new LambdaQueryWrapper<CreativeScriptScene>()
                .eq(CreativeScriptScene::getScriptId, scriptId)
                .eq(CreativeScriptScene::getShotStatus, status)
                .orderByDesc(CreativeScriptScene::getUpdateTime)
                .last("LIMIT 10"));

        // 转换为 VO 对象
        return list.stream().map(item -> {
            CreativeScriptSceneListVO vo = new CreativeScriptSceneListVO();
            BeanUtils.copyProperties(Objects.requireNonNull(item), vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean updateShotStatus(String sceneId, String currentStatus, String targetStatus) {
        return update(new LambdaUpdateWrapper<CreativeScriptScene>()
                .eq(CreativeScriptScene::getSceneId, sceneId)
                .eq(CreativeScriptScene::getShotStatus, currentStatus)
                .set(CreativeScriptScene::getShotStatus, targetStatus));
    }

    @Override
    public boolean edit(CreativeScriptSceneEditDTO dto) {
        CreativeScriptScene entity = new CreativeScriptScene();
        BeanUtils.copyProperties(Objects.requireNonNull(dto), entity);
        return updateById(entity);
    }

}